import React from "react";
import Draggable from 'react-draggable'
import { store } from "./store";

export default class Drap extends React.Component{
  public ref:any

  public catch:any = {}

  public state = {
    activeDrags: 0,
    deltaPosition: {
      x: 0, y: 0
    },
    controlledPosition: {
      x: -150, y: -500
    }
  }

  public onStart = (...args:any[])  => {
    console.log(args)
    this.setState({activeDrags: ++this.state.activeDrags});
  }

  public onStop = (...args:any[]) => {
    console.log(args)
    this.setState({})
    this.setState({activeDrags: --this.state.activeDrags});
  }


  public onControlledDrag = (e:any, position:any) => {
    const {x, y} = position;
    const positions = [
      [this.catch.offsetLeft + x, this.catch.offsetTop + y],
      [this.catch.offsetLeft + x + this.catch.clientWidth, this.catch.offsetTop + y],
      [this.catch.offsetLeft + x, this.catch.offsetTop + y + this.catch.clientHeight],
      [this.catch.offsetLeft + x + this.catch.clientWidth, this.catch.offsetTop + y + this.catch.clientHeight],
    ]
    store.next({ positions })
    // this.setState({controlledPosition: {x, y}});
  }

  public handleDrag = (e:any, ui:any) => {
    const {x, y} = this.state.deltaPosition;
    this.setState({
      deltaPosition: {
        x: x + ui.deltaX,
        y: y + ui.deltaY,
      }
    });
  }

  public componentDidMount(){
    this.catch.offsetLeft = this.ref.offsetLeft
    this.catch.offsetTop = this.ref.offsetTop
    this.catch.clientHeight = this.ref.clientHeight
    this.catch.clientWidth = this.ref.clientWidth
  }

  public render () {
    const dragHandlers = {onStart: this.onStart, onStop: this.onStop};
    const {controlledPosition} = this.state;
    return (
      <Draggable position={controlledPosition} onDrag={this.onControlledDrag} {...dragHandlers}>
      <div ref={(ref) => this.ref = ref} className="box" style={{ width: 100, background: 'red' }}>
        <div>I track my deltas</div>
        <div>x: {controlledPosition.x.toFixed(0)}, y: {controlledPosition.y.toFixed(0)}</div>
      </div>
    </Draggable>  
    )
  }
}